/*****************************************************************************
 * HUSONG PROPRIETARY INFORMATION
 * <p/>
 * The information contained herein is proprietary to HUSONG
 * and shall not be reproduced or disclosed in whole or in part
 * or used for any design or manufacture
 * without direct written authorization from HUSONG.
 * <p/>
 * Copyright (c) 2015 by HUSONG.  All rights reserved.
 *****************************************************************************/
package com.husong.common.shiro.filter;

import com.alibaba.fastjson.JSON;
import com.husong.common.shiro.Constants;
import com.husong.common.shiro.realm.StatelessToken;
import com.husong.cons.ReturnCodeAndMsg;
import com.husong.pojo.ReturnJsonBean;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author maxmin
 */
public class StatelessAuthcFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    	request.setCharacterEncoding("UTF-8");
        // 1、客户端生成的消息摘要
        String digest = request.getParameter(Constants.PARAM_DIGEST);
        digest = digest==null?"":digest;
        System.out.println("digest:"+digest);
        // 2、客户端传入的用户身份
        String secretKey = request.getParameter(Constants.PARAM_KEY);
        System.out.println("secretKey:"+secretKey);
        // 3、客户端请求的参数列表
        Map<String, String[]> params = new HashMap<String, String[]>(request.getParameterMap());
        params.remove(Constants.PARAM_DIGEST);
        params.remove(Constants.PARAM_KEY);

        // 4、生成无状态Token
        StatelessToken token = new StatelessToken(secretKey, params, digest.toUpperCase());
        try {
            // 5、委托给Realm进行登录
            getSubject(request, response).login(token);
        } catch (Exception e) {
            // 6、登录失败
            onLoginFail(response);
            // TODO: 2015/11/11  增加请求失败的记录
            //e.printStackTrace();
            return false;
        }
        return true;
    }

    // 登录失败
    private void onLoginFail(ServletResponse response) throws IOException {
        PrintWriter writer = null;
        try {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            httpResponse.setCharacterEncoding("UTF-8");
            httpResponse.setContentType("text/html; charset=utf-8");
            writer = httpResponse.getWriter();
            ReturnJsonBean rb = new ReturnJsonBean();
            rb.setCode(ReturnCodeAndMsg.UNAUTHORIZED);
            rb.setMessage(ReturnCodeAndMsg.UNAUTHORIZED_MSG);
            String str = JSON.toJSONString(rb);
            writer.write(str);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }
    }

}
